package db

import (
	"database-platform/dal"
	"database-platform/logger"
	"database-platform/model"
	"fmt"
	"time"
)

func ListAccountRecords(account *model.Account, page, pageSize int64, search string, showCluster, showDatabase bool) ([]*model.Account, uint64, error) {
	var query = dal.GORM
	var records []*model.Account
	var count uint64

	if account.Username != "" {
		query = query.Where("username = ?", account.Username)
	}
	if account.UserType != "" {
		query = query.Where("user_type = ?", account.UserType)
	}
	if account.ClusterID != nil {
		query = query.Where("cluster_id = ?", account.ClusterID)
	}
	if account.DatabaseID != nil {
		query = query.Where("database_id = ?", account.DatabaseID)
	}
	if account.DBType != "" {
		query = query.Where("db_type = ?", account.DBType)
	}

	if search != "" {
		query = query.Where("username like ?", "%"+search+"%")
	}

	if page > 0 && pageSize > 0 {
		offset := (page - 1) * pageSize
		query = query.Offset(offset).Limit(pageSize)
	}

	if showCluster {
		query = query.Preload("Cluster")
	}
	if showDatabase {
		query = query.Preload("Database")
	}

	err := query.Find(&records).Count(&count).Error
	if err != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.account.ListAccountRecords sql execute err, err message is %s, account: %v", err, account)
		logger.Logger.Error(msg)
		return nil, 0, err
	}
	return records, count, nil
}

func GetAccountRecordById(id int) (record *model.Account, err error) {
	record = &model.Account{}
	tx := dal.GORM.Where("id = ?", id).First(&record)
	if tx.Error != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.account.GetAccountRecordById.sql.execute.err.message.%s.id.%v", tx.Error, id)
		logger.Logger.Error(msg)
		return nil, tx.Error
	}

	return record, nil
}

// InsertAccountRecord 插入账号记录
func InsertAccountRecord(account *model.Account) error {
	account.UpdateTime = time.Now()
	account.CreateTime = time.Now()
	err := dal.GORM.Create(account).Error
	if err != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.account.InsertAccountRecord sql execute err, err message is %s, account: %v", err, account)
		logger.Logger.Error(msg)
		return err
	}
	return nil
}

// UpdateAccountRecord 更新账号记录
func UpdateAccountRecord(id int, account *model.Account) error {
	account.UpdateTime = time.Now()
	account.ID = int64(id)
	err := dal.GORM.Save(account).Error
	if err != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.account.UpdateAccountRecord sql execute err, err message is %s, account: %v", err, account)
		logger.Logger.Error(msg)
		return err
	}
	return nil
}

// DeleteAccountRecord 删除账号记录
func DeleteAccountRecord(id int) error {
	err := dal.GORM.Delete(&model.Account{}, id).Error
	if err != nil {
		msg := fmt.Sprintf("【DB.LOG】 db.account.DeleteAccountRecord sql execute err, err message is %s, id: %d", err, id)
		logger.Logger.Error(msg)
		return err
	}
	return nil
}
